import xl from '@/assets/images/tj.png';
import yc from '@/assets/images/yc.png';
import hc from '@/assets/images/hc.png';
import hs from '@/assets/images/hs.png';
import jd from '@/assets/images/jd.png';
import wsj from '@/assets/images/wsj.png';
import tcc from '@/assets/images/tcc.png';

import xlActive from '@/assets/images/xl_active.png';
import ycActive from '@/assets/images/yc_active.png';
import hcActive from '@/assets/images/hc_active.png';
import hsActive from '@/assets/images/hs_active.png';
import jdActive from '@/assets/images/jd_active.png';
import wsjActive from '@/assets/images/wsj_active.png';
import tccActive from '@/assets/images/tcc_active.png';
import { useRoute } from 'vue-router';
import { ref, watch, toRef } from 'vue';
import L from 'leaflet';
import './../helper/MovingMarker';

export default ({ mapId }) => {
    let map = null;
    let baseLayer = null;
    // 1景点,2中餐,3茶饮,4小吃,5酒店,6公共厕所,7停车场,8游客中心,9医务室,10演出,11管理局
    const typeMap = {
        xl: xl,
        10: yc,
        3: hc,
        4: hs,
        1: jd,
        6: wsj,
        7: tcc,
    }

    const typeMapActive = {
        xl: xlActive,
        10: ycActive,
        3: hcActive,
        4: hsActive,
        1: jdActive,
        6: wsjActive,
        7: tccActive,
    }

    const removeAllLayer = () => {
        map.eachLayer((layer) => {
            if (layer !== baseLayer) {
                map.removeLayer(layer);
            }
        });
    }
    const createMarker = (data, type, handler) => {
        const titleText = data.title || data.businessName;
        let titleW = titleText ? titleText.length + 0.2 : 1.2;
        const icon = L.divIcon({
            className: 'my-div-icon',
            html: `
                <div class="cus-marker">
                    <div class="title" style="width:${titleW}em;">${titleText}</div>
                    <img class="icon" src="${typeMap[type]}" alt="" srcset="">
                </div>
                `,
        });
        const marker = L.marker([data.positioningLat, data.positioningLng], {
            icon: icon,
        });
        marker.on('click', (e) => {
            console.log(e);
            handler && handler(data);
        })
        return marker;
    }

    const addMaker = (makers = [], type = 1, handler) => {
        removeAllLayer();
        const _makers = makers.map(data => { return createMarker(data, type, handler); })
        const _markersGroup = L.layerGroup(_makers);
        map.addLayer(_markersGroup);
    }

    const addPolyline = (polyline = [], type = 1, handler) => {
        removeAllLayer();

        const _polyline = polyline.map(data => {
            return [data.positioningLat, data.positioningLng]
        })
        const icon = L.icon({
            iconUrl: './imgs/location_icon.png',
            iconSize: [24, 30],
        });
        const marker2 = L.Marker.movingMarker(_polyline, 500 * _polyline.length, {
            icon: icon,
            zIndexOffset: 100
        }).addTo(map);
        let path = [] // 声明绘制线的临时使用变量
        marker2.on('move', res => { // 监听点位移动事件 move
            map.panTo([res.latlng.lat, res.latlng.lng]) //回调中会返回经纬度信息，点移动改变地图中心点
            path.length > 1 && path.shift() // 保持数组长度，避免过度push不断重新绘制之前的路径
            path.push([res.latlng.lat, res.latlng.lng]) // 将数据push到数组中
            L.polyline(path, { color: '#4685FF', weight: 6 }).addTo(map) // 绘制线到地图图层
        })
        marker2.start();
        const _makers = polyline.filter(item => {
            return item.lables == 1
        }).map(data => {
            return createMarker(data, { 1: 3, 2: 4 }[type]  || 1, handler);
        })
        // const _markersGroup = L.layerGroup(_makers, {});
        _makers.forEach((item) => {
            map.addLayer(item);
        })
    }

    const route = useRoute();
    const isAdmin = route.query.isAdmin;
    const rightTop = [30.33406492512, 103.98250579834];
    const leftBottom = [30.311245603935, 103.96448135376];
    const bounds = L.bounds([leftBottom, rightTop]);

    const init = () => {
        map = L.map(mapId, {
            center: [30.316931991254904, 103.9705538749695],
            zoom: 16,
            zoomControl: false,
            minZoom: 16,
            maxZoom: 19,
            maxBounds: [rightTop, leftBottom]
        })

        baseLayer = L.tileLayer('https://hlximage.xiangle6.cn/home/leaflet/{z}/{x}_{y}.png',
            {
                minZoom: 16,
                maxZoom: 19,
            }
        ).addTo(map);

        if (isAdmin) {
            map.on('click', function (e) {
                const str = e.latlng.lat + ',' + e.latlng.lng
                console.log(e);
                alert(str);
            });
        }
    }

    const getLocation = async () => {
        return new Promise((resolve, reject) => {
            map.on('locationfound', (res) => {
                resolve(res);
            })
            map.on('locationerror', (err) => {
                reject(err);
            })
            map.locate();
        })
    }

    const toastShow = ref(false);
    const toastText = ref('');
    let toastTimer = null;
    watch(toastShow, (val) => {
        if (val) {
            if (toastTimer) {
                clearTimeout(toastTimer);
            }
            toastTimer = setTimeout(() => {
                toastShow.value = false;
                toastText.value = '';
            }, 2000)
        }
    })

    let centerMarker = null;
    let currentLocation = null;
    const setLocationCenter = async () => {
        try {
            if (centerMarker) {
                map.removeLayer(centerMarker);
            }
            try {
                // 获取当前定位
                const res = await getLocation();
                console.log('res', res);
                let radius = res.accuracy / 2;
                radius = radius > 300 ? 50 : radius;
                currentLocation = PointTransformation.gcj_encrypt(res.latlng.lat, res.latlng.lng);
                const latLngBounds = L.latLngBounds([rightTop, leftBottom]);
                if (latLngBounds.contains(res.latlng)) {
                    const latlng = res.latlng
                    const icon = L.icon({
                        iconUrl: './imgs/location_icon.png',
                        iconSize: [24, 30],
                    });
                    centerMarker = L.marker(latlng, { icon })
                    map.addLayer(centerMarker);
                    map.panTo(latlng);
                } else {
                    toastShow.value = true;
                    toastText.value = '您不在景区内';
                }
            } catch (error) {
                toastShow.value = true;
                toastText.value = '定位失败，请开启定位权限';
            }

        } catch (error) {
            console.log(error);
        }
    };

    const PointTransformation = {
        PI: 3.14159265358979324,
        x_pi: 3.14159265358979324 * 3000.0 / 180.0,
        delta: function (lat, lon) {
            var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
            var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
            var dLat = this.transformLat(lon - 105.0, lat - 35.0);
            var dLon = this.transformLon(lon - 105.0, lat - 35.0);
            var radLat = lat / 180.0 * this.PI;
            var magic = Math.sin(radLat),
                magic = 1 - ee * magic * magic;
            var sqrtMagic = Math.sqrt(magic),
                dLat = dLat * 180.0 / (a * (1 - ee) / (magic * sqrtMagic) * this.PI),
                dLon = dLon * 180.0 / (a / sqrtMagic * Math.cos(radLat) * this.PI);
            var pt = {
                lat: dLat,
                lon: dLon
            };
            return pt;
        },

        //WGS-84 to GCJ-02
        gcj_encrypt: function (wgsLat, wgsLon) {
            if (this.outOfChina(wgsLat, wgsLon))
                return { lat: wgsLat, lng: wgsLon };

            var d = this.delta(wgsLat, wgsLon);
            var pt = {
                lat: wgsLat + d.lat,
                lng: wgsLon + d.lon
            };
            return pt;
        },
        outOfChina: function (lat, lon) {
            if (lon < 72.004 || lon > 137.8347)
                return true;
            if (lat < 0.8293 || lat > 55.8271)
                return true;
            return false;
        },
        transformLat: function (x, y) {
            var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
            return ret;
        },
        transformLon: function (x, y) {
            var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
            return ret;
        }
    };

    const addMapEventListener = (type, fn) => {
        map.on(type, fn);
    }

    return { addMapEventListener, stop, map, init, addMaker, addPolyline, getLocation, setLocationCenter, PointTransformation, toastShow, toastText }
}
